<?php


namespace app\admin\controller;


use app\common\model\StatUserCheckinModel;
use app\common\model\UserStatisticsModel;
use think\facade\Request;

class UserCheckinController extends BaseController
{
    /**
     * 签到统计列表
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 数据列表
     * @return \think\response\Json
     */
    public function getlist()
    {
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");
        // 分页
        $page  = Request::param("page");
        $limit = Request::param("limit");

        $where = [];
        if ($start_time) {
            $where[] = ['stt_date', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['stt_date', '<=', $end_time];
        }

        $count = StatUserCheckinModel::where($where)->count("id");

        if ($count > 0) {
            $notice = StatUserCheckinModel::where($where)
                ->order('stt_date desc')
                ->page($page, $limit)
                ->select();

            return json(["code" => 0, "msg" => "", "data" => $notice, "count" => $count]);
        }

        return self::bulidFail('暂无数据');
    }

    /**
     * 导出excel
     * @throws \think\exception\DbException
     */
    public function excel()
    {
        set_time_limit(0);
        $start_time = Request::param("start_time");
        $end_time   = Request::param("end_time");

        $where = [];
        if ($start_time) {
            $where[] = ['stt_date', '>=', $start_time];
        }
        if ($end_time) {
            $where[] = ['stt_date', '<=', $end_time];
        }


        $statis_model = StatUserCheckinModel::where($where);

        $list = [];
        $statis_model->chunk(500, function ($querys) use (&$list) {
            foreach ($querys as $query) {
                $list[] = [
                    $query->stt_date,
                    $query->time_1,
                    $query->time_2,
                    $query->time_3,
                    $query->time_4,
                    $query->time_5,
                    $query->time_6,
                    $query->time_7,
                    $query->over_time_8,
                ];
            }
        }, 'stt_date', 'desc');

        $file_title = ['统计时间', '签到1次', '签到2次', '签到3次', '签到4次', '签到5次', '签到6次', '签到7次', '签到8次及以上'];

        // 记录日志
        $file_name = '签到统计';
        parent::addAdminLog("导出{$file_name}报表");

        $file_name = $file_name . date('Y年m月d日H点');
        return export_excel($list, $file_title, $file_name, $file_name);
    }

}
